package dk.dtu.android.transport;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EncodingUtils;
import org.json.JSONObject;

import android.util.Log;

public class RestClient {
	private static String convertStreamToString(InputStream is)
	{
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try
		{
			while ((line = reader.readLine()) != null)
			{
				sb.append(line + "\n");
			}
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				is.close();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
	
	public static String EncodeURL(String url, List<NameValuePair> params)
	{
		if (!params.isEmpty())
		{
			if(!url.endsWith("?"))
		        url += "?";
			url += URLEncodedUtils.format(params, "utf-8");
		}
		return url;
	}

	public static String post(String url, String json) throws ClientProtocolException, IOException
	{
		DefaultHttpClient httpclient = new DefaultHttpClient();
		
		HttpPost httppost = new HttpPost(url);
		httppost.setHeader("type", "POST");
		httppost.setHeader(HTTP.CONTENT_TYPE, "text/json; charset=utf-8");
		
		HttpResponse response;
		
		// Insert the json object to the POST request
		StringEntity se;
	    se = new StringEntity(EncodingUtils.getString(json.getBytes(), "iso-8859-1"));
		Log.d("RestClient", "Sending POST request: " + json);
		se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json; charset=utf-8"));
		httppost.setEntity(se);
		response = httpclient.execute(httppost);
		Log.d("RestClient", response.getStatusLine().toString());
		
		HttpEntity entity = response.getEntity();
		
		if (entity != null)
		{
		  InputStream instream = entity.getContent();
		  return convertStreamToString(instream);
		}
		return null;
	}
	public static String post(String url, JSONObject jsonObj) throws ClientProtocolException, IOException
	{
		return post(url, jsonObj.toString());
	}

	/*public static String post(String url, Map params)
	throws Exception 
	{

		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpPost httpost = new HttpPost(url);
		Iterator iter = params.entrySet().iterator();
	
		JSONObject holder = new JSONObject();
	
		while(iter.hasNext()) {
			Map.Entry pairs = (Map.Entry)iter.next();
			String key = (String)pairs.getKey();
			Map m = (Map)pairs.getValue();
			   
			JSONObject data = new JSONObject();
			Iterator iter2 = m.entrySet().iterator();
			while(iter2.hasNext()) {
				Map.Entry pairs2 = (Map.Entry)iter2.next();
				data.put((String)pairs2.getKey(), (String)pairs2.getValue());
			}
			holder.put(key, data);
		}
	
		StringEntity se = new StringEntity(holder.toString());
		httpost.setEntity(se);
		httpost.setHeader("Accept", "application/json");
		httpost.setHeader("Content-type", "application/json");
	
		ResponseHandler responseHandler = new BasicResponseHandler();
		response = httpclient.execute(httpost, responseHandler);
	}*/
	
	public static String get(String url) throws ClientProtocolException, IOException
	{
		return get(url, new LinkedList<NameValuePair>());
	}
	
	public static String get(String url, List<NameValuePair> params) throws ClientProtocolException, IOException
	{
		url = EncodeURL(url, params);
		
		DefaultHttpClient httpclient = new DefaultHttpClient();
		
		HttpGet httpget = new HttpGet(url);
		httpget.setHeader("type", "GET");
		httpget.setHeader(HTTP.CONTENT_TYPE, "application/json; charset=utf-8");

		HttpResponse response;
		
		response = httpclient.execute(httpget);
		// Examine the response status
		Log.i("RestClient",response.getStatusLine().toString());
		
		// Get hold of the response entity
		HttpEntity entity = response.getEntity();
		// If the response does not enclose an entity, there is no need
		// to worry about connection release
		
		if (entity != null)
		{
		  InputStream instream = entity.getContent();
		  return convertStreamToString(instream);
		}
		return null;

	}
}
